<template>
  <div class="avatar-box">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="onUpload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: [String, Array, Object],
      default: ''
    }
  },
  methods: {
    // 配置上传
    // 1. 定义 http-request 属性， 该属性可以自定义上传， 接收一个函数
    // 2. 引入腾讯云COS
    // 3. 函数内部， 配置腾讯云COS
    onUpload(event) {
      const cosObj = new COS({
        SecretId: 'AKIDjHnYHmzwwoETUGlGfx658xYtxkHm7C1a',
        SecretKey: 'WpwpaAYgZCav75ziCSkvvfAPXSYXKvHM'
      })

      cosObj.putObject({
        // 存储桶名称
        Bucket: 'test-yun-1317783713',
        // 所属地域
        Region: 'ap-hongkong',
        // 文件名称
        Key: event.file.name,
        // 固定值
        StorageClass: 'STANDARD',
        // 上传文件对象
        Body: event.file
      }, (err, data) => {
        if (err) {
          console.log(err)
          // this.$message.error(err)
        } else {
          console.log('data', data)
          this.$emit('input', data.Location)
        }
      })
    },
    // 上传成功
    handleAvatarSuccess(response, file, fileList) {
      console.log(response, file, fileList)
      this.$emit('input', URL.createObjectURL(file.raw))
    },
    // 上传前的钩子函数
    beforeAvatarUpload(file) {
      // console.log(file)
      const whileList = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
      const isJPG = whileList.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG / PNG / JPEG / GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
